﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace Tomahawk.Runtime.Timeline
{
    public class AnimatedTextureEffectTrack : SpriteEffectTrack
    {
        [XmlElement("SpriteCount")]
        public int spriteCount = 1;

        [XmlElement("Speed")]
        public string speed = "";

        [XmlElement("DefaultSpeed")]
        public float defaultSpeed = 4.0f;

        private float lastTime = 0.0f;
        private float currentSpeed = 0.0f;
        private float currentSprite = 0.0f;
        private Curve curveSpeed = new Curve();

        public AnimatedTextureEffectTrack() : base() { }

        public AnimatedTextureEffectTrack(string name) : base(name) { }

        protected override string GetEffectFile()
        {
            return @"Tomahawk.Content\SpriteEffects\AnimatedTextureEffect";
        }

        protected override void OnLoadEffectParameters(Effect effect)
        {
            float sprite = (float) Math.Round(currentSprite);
            sprite = MathHelper.Clamp(sprite, 0, spriteCount - 1);

            effect.Parameters["SpriteCount"].SetValue(spriteCount);
            effect.Parameters["CurrentSprite"].SetValue((int) sprite);
        }

        protected override bool OnLoad(GraphicsDevice graphics, ContentManager contentManager)
        {
            curveSpeed = LoadCurve(contentManager, speed);
            return base.OnLoad(graphics, contentManager);
        }

        public override void SortKeys() { }

        public override bool Update(float time)
        {
            currentSpeed = curveSpeed != null ? curveSpeed.Evaluate(time) : defaultSpeed;
            currentSprite += currentSpeed * (time - lastTime);
            currentSprite %= spriteCount;
            lastTime = time;

            return true;
        }
    }
}
